package com.zcc.makingfriend.service.impl;

import com.zcc.makingfriend.dao.*;
import com.zcc.makingfriend.dto.ArticleCategoryDto;
import com.zcc.makingfriend.dto.ArticleImageDto;
import com.zcc.makingfriend.dto.PageDto;
import com.zcc.makingfriend.mapper.*;
import com.zcc.makingfriend.service.ArticleService;
import com.zcc.makingfriend.service.AttachmentService;
import com.zcc.makingfriend.untils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @author zcc
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private LikedMapper likedMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private TbArticleCategoryMapper tbArticleCategoryMapper;

    @Autowired
    private TbUserArticleMapper tbUserArticleMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TbUserConcernedMapper tbUserConcernedMapper;

    public List<ArticleImageDto> handArticle(List<Article> allArticles, String userId) {
        List<ArticleImageDto> articleImageDtos = new ArrayList<>();
        for (int i = 0; i < allArticles.size(); i++) {
            Article article = allArticles.get(i);
            User user = userMapper.findUserById(article.getAuthorId());
            article.setAuthor(user != null? user.getUsername(): "废弃文章");
            String uuid = article.getUuid();
            String categoryUuid = tbArticleCategoryMapper.getCategoryUuidByArticleUuid(uuid);
            Category categoryByUuid = categoryMapper.findCategoryByUuid(categoryUuid);

            List<Image> imageByArticleId = imageMapper.findImageByArticleId(uuid);
            ArticleImageDto articleImageDto = new ArticleImageDto(article, imageByArticleId);
            articleImageDto.setSortTitle(categoryByUuid == null? "" : categoryByUuid.getTitle() );
            articleImageDtos.add(articleImageDto);;
            if (userId != null) {
                Liked liked = likedMapper.getLiked(uuid, userId);
                // liked为空表示用户未点赞
                articleImageDto.setLiked(liked != null);
            }
        }
        return articleImageDtos;
    }

    @Override
    public List<ArticleImageDto> getAllArticles(String userId, int page, int size){
        List<Article> allArticles = articleMapper.getAllArticles(page, size);
        return handArticle(allArticles, userId);
    }

    @Override
    public List<ArticleImageDto> getAllArticlesByCategory(String title, String userId, int page, int size) {
        Category categoryByTitle = categoryMapper.findCategoryByTitle(title);
        List<TbArticleCategory> tbArticleCategoryByCategoryUuid = tbArticleCategoryMapper.findTbArticleCategoryByCategoryUuid(categoryByTitle.getUuid(), page, size);
        List<Article> articles = new ArrayList<>();
        for (TbArticleCategory tbArticleCategory: tbArticleCategoryByCategoryUuid) {
            String articleId = tbArticleCategory.getArticleId();
            Article articleByUuid = articleMapper.getArticleByUuid(articleId);
            articles.add(articleByUuid);
        }
        return handArticle(articles, userId);
    }

    @Override
    public List<ArticleImageDto> getAllArticlesByUser(String userId) {
        User userByUuid = userMapper.findUserByUuid(userId);
        Long id = userByUuid.getId();
        List<TbUserConcerned> concerneds = tbUserConcernedMapper.getConcerneds(id);
        List<Article> articles = new ArrayList<>();
        for (TbUserConcerned concerned : concerneds) {
            Long concernedId = concerned.getConcernedId();
            List<Article> allArticleById = articleMapper.getAllArticleById(concernedId);
            articles.addAll(allArticleById);
        }
        articles.sort(Comparator.comparing(Article::getUpdated).reversed());
        return handArticle(articles, userId);
    }

    @Override
    public List<ArticleImageDto> searchArticle(String content, String userId, int page, int size) {
        List<Article> articles = articleMapper.searchArticle(content, page, size);
        return handArticle(articles, userId);
    }

    @Override
    public List<ArticleImageDto> getLikeArticles(String userId, int page, int size) {
        List<Liked> likeds = likedMapper.findLikeds(userId, page, size);
        List<Article> articles = new ArrayList<>();
        for (int i = 0; i < likeds.size(); i++) {
            Liked liked = likeds.get(i);
            Article articleByUuid = articleMapper.getArticleByUuid(liked.getArticleId());
            articles.add(articleByUuid);
        }
        List<ArticleImageDto> articleImageDtos = handArticle(articles, userId);
        return articleImageDtos;
    }

    @Override
    public Long countUserLiked(String userId) {
        return likedMapper.countUserLikes(userId);
    }

    @Override
    public List<ArticleImageDto> getArticleByAuthor(Long authorId, int page, int size) {
        List<Article> articleByAuthor = articleMapper.getArticleByAuthor(authorId, page, size);
        User userById = userMapper.findUserById(authorId);
        List<ArticleImageDto> articleImageDtos = handArticle(articleByAuthor, userById.getUuid());
        return articleImageDtos;
    }

    @Override
    public List<ArticleImageDto> getArticlesByCondition(PageDto pageDto) {
        pageDto.setPage((pageDto.getPage() - 1) * pageDto.getSize());
        List<Article> articlesByCondition = articleMapper.getArticlesByCondition(pageDto);
        return handArticle(articlesByCondition, null);
    }

    ;

    @Override
    public ArticleImageDto getArticleByUUid(String uuid){
        Article article = articleMapper.getArticleByUuid(uuid);
        User userById = userMapper.findUserById(article.getAuthorId());
        String categoryUuid = tbArticleCategoryMapper.getCategoryUuidByArticleUuid(uuid);
        Category categoryByUuid = categoryMapper.findCategoryByUuid(categoryUuid);
        List<Image> imageByArticleId = imageMapper.findImageByArticleId(uuid);
        article.setAuthor(userById != null?userById.getUsername() : "文章已经废弃");
        ArticleImageDto articleImageDto = new ArticleImageDto(article, imageByArticleId);
        articleImageDto.setSortTitle(categoryByUuid == null? "" : categoryByUuid.getTitle() );
        return articleImageDto;
    }

    @Override
    public String addArticle(ArticleCategoryDto articleCategoryDto) {
        String title = articleCategoryDto.getTitle();
        Category categoryByTitle = categoryMapper.findCategoryByTitle(title);
        String categoryUUid = categoryByTitle.getUuid();
        Article article = articleCategoryDto.getArticle();
        String uuid = UUID.randomUUID().toString();
        Long authorId = articleCategoryDto.getArticle().getAuthorId();
        User userById = userMapper.findUserById(authorId);
        if (userById.getStatus() == 1) {
            return "0";
        } else {
            // 新增文章分类中间表
            int j = tbArticleCategoryMapper.addTbArticleCategory(new TbArticleCategory(categoryUUid, uuid));
            LocalDateTime created = LocalDateTime.now();
            article.setUuid(uuid);
            article.setCreated(created);
            article.setUpdated(created);
            article.setImgUrl(uuid);
            article.setLikes(0L);
            article.setStatus(0);
            int x = tbUserArticleMapper.addTbUserArticle(new TbUserArticle(uuid, article.getAuthorId()));
            int i = articleMapper.addArticle(article);
            return i == 1 && j == 1 && x == 1? uuid : null;
        }
    }

    @Override
    public int deleteArticle(String uuid) {
        int i = articleMapper.deleteArticle(uuid);
        int j = tbArticleCategoryMapper.deleteTbArticleCategoryByArticleId(uuid);
        return i > 0 && j > 0 ? 1 : 0;
    }

    @Override
    public String updateArticle(ArticleCategoryDto articleCategoryDto) {
        Article article = articleCategoryDto.getArticle();
        String title = articleCategoryDto.getTitle();
        Category categoryByTitle = categoryMapper.findCategoryByTitle(title);
        String categoryUuid = categoryByTitle.getUuid();
        // 修改文章分类中间表
        int j = tbArticleCategoryMapper.updateTbArticleCategory(new TbArticleCategory(categoryUuid, article.getUuid()));
        LocalDateTime updated = LocalDateTime.now();
        article.setUpdated(updated);
        int i = articleMapper.updateArticle(article);
        System.out.println(i + "\t" + j);
        return i == 1 && j == 1 ? article.getUuid() :null;
    }

    @Override
    public int isLikeArticle(int status, int likes, String uuid) {
        int likeArticle = articleMapper.isLikeArticle(likes + status, uuid);
        if (likeArticle == 1) {
            return likes + status;
        }
        return likes;
    }

    @Override
    public Long countArticles() {
        return articleMapper.countArticles();
    }

    @Override
    public Long countConditionArticles(PageDto pageDto) {
        return articleMapper.countConditionArticles(pageDto);
    }

    @Override
    public Long countReportArticle() {
        return articleMapper.countReportArticle();
    }

    @Override
    public Map<String, Long> countArticleByCategory() {
        Map<String, Long> stringLongMap = new HashMap<>();
        List<Category> allCategory = categoryMapper.findAllCategory();
        for (Category category: allCategory) {
            String title = category.getTitle();
            String categoryUuid = category.getUuid();
            Long aLong = tbArticleCategoryMapper.countArticleByCategoryUuid(categoryUuid);
            stringLongMap.put(title, aLong);
        }
        return stringLongMap;
    }

    @Override
    public Map<String, Long> countArticleByUser() {
        Map<String, Long> stringLongMap = new HashMap<>();
        List<User> all = userMapper.getAll();
        for (User user: all) {
            String username = user.getUsername();
            Long aLong = tbUserArticleMapper.countArticleByUserId(user.getId());
            stringLongMap.put(username, aLong);
        }
        return stringLongMap;
    }

    @Override
    public List<ArticleImageDto> findReportArticleByCondition(PageDto pageDto) {
        pageDto.setPage((pageDto.getPage() - 1) * pageDto.getSize());
        List<Article> articlesByCondition = articleMapper.findReportArticleByCondition(pageDto);
        return handArticle(articlesByCondition, null);
    }

    @Override
    public Long countConditionReportArticles(PageDto pageDto) {
        return articleMapper.countConditionReportArticles(pageDto);
    }


}
